#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/4 14:58
# @Author  : leon yan
# @Site    : 
# @File    : pyCoating.py
# @Software: PyCharm

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox

import Globalist as gl
# from EncryptionRd import QReadLicense
from MainWindow import QObjWindow
# import Class.qSqlEdit as DbSql
from lib.qpulsesignal import Qhalfclocksignal
from resource.pyCoating_ui import Ui_Form

from loguru import logger
# from mylog import logger


class QPyCoating(QWidget, Ui_Form):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        gl.init()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.label.setText("加载中...")
        self.labelStepName.setText("")
        # '''启动脉冲线程'''
        self.eBar = 0
        # 临时注释掉
        self.clockSignal = Qhalfclocksignal()
        self.clockSignal.start()
        self.clockSignal.bhalfclock.connect(self.doInitialization)
        ''''''
        self.eMax = 9
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(self.eMax)
        ''''''
        self.objMainWin = None
        self._pic = QPixmap(r".\\resource\\icons\\StartImage3.png")  # 载入背景图片到内存，提高绘制速度
        self.initDone = False
        '''log'''
        self.log = logger
        self.log.add(sink=r".\log\log.log", format="{time} - {level} - {message}", level='INFO', rotation='1 day')

    def __del__(self):
        print("pyLogisticsOne is deleted")

    def paintEvent(self, event):
        painter = QPainter(self)
        eWidth = 800
        eHeight = 480
        painter.drawPixmap(0, 0, eWidth, eHeight, self._pic)
        super().paintEvent(event)

    def loadMainWin(self):
        pass
        self.objMainWin = QObjWindow()  # 必须传递self，否则无法显示
        self.objMainWin.setAttribute(Qt.WA_DeleteOnClose)
        self.objMainWin.show()

    def startMain(self):
        # 临时注释掉
        if not self.doVerification():
            return
        else:
            self.deleteLater()
            self.loadMainWin()

    def doVerification(self):
        return True
        rdMac = gl.get_value('AuthorizationMac')
        thisMac = gl.get_mac_address()
        return True
        if rdMac is None:
            QMessageBox.critical(self, "错误", "本机未授权!")
            return None
        else:
            if thisMac not in rdMac:
                QMessageBox.critical(self, "错误", "本机未授权!")
                return None
            else:
                return True

    def doInitialization(self):
        # self.startMain()
        """初始化过程"""
        # print(self.eBar)
        if self.eBar < self.eMax:
            if self.eBar == 0:
                self.labelStepName.setText("Global variable initial...")
                gl.init()
            if self.eBar == 1:
                self.labelStepName.setText("systemVariable initial")
                gl.systemVariable()
            if self.eBar == 2:
                self.labelStepName.setText("device initial")
                gl.deviceInitial()
                gl.initialPlc()
            if self.eBar == 3:
                self.labelStepName.setText("License variable initial")
                # gl.initLicenseVar()
            if self.eBar == 4:
                self.labelStepName.setText("Read authorization")
                # QReadLicense().readLicense()
            if self.eBar == 5:
                self.labelStepName.setText("Read configuration file")
                gl.initial_cfg()
            if self.eBar == 6:
                pass
            if self.eBar == 7:
                pass
            if self.eBar == 8:
                self.labelStepName.setText("Initial OK")
            self.eBar += 1
            self.progressBar.setValue(self.eBar)
            if self.eBar >= 9:
                self.log.info("300 Initial ok!")
                self.startMain()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    objWindow = QPyCoating()
    objWindow.show()
    sys.exit(app.exec_())
